package BLC

import (
	"flag"
	"fmt"
	"os"
)

type CLI struct {
	blockchain *BlockChain
}

func NewCLI(bc *BlockChain) *CLI {
	return &CLI{bc}
}

//打印参数,打印要求的参数
func (cli *CLI) PrintUsage() {
	fmt.Println("Usage:")
	fmt.Println("Usage of addblock: -data string 这个东西是为了添加数据到data中")
	fmt.Println("Usage of printblock: 请正确输入参数和命令！")
}

//打印整个区块链
func (cli *CLI) PrintBlockChain() {
	cli.blockchain.ViewBlockChain()
}

//测试打包多个交易用的
func (cli *CLI) sendToken() {
	//tx1:=NewUTXOTransaction("lidabao","dandan",3,cli.blockchain)
	tx2 := NewUTXOTransaction("lidabao", "awang", 2, cli.blockchain)

	cli.blockchain.Miner([]*Transaction{tx2})

	cli.blockchain.ViewBlockChain()
}

//添加区块
func (cli *CLI) AddBlock(data string) {
	//cli.blockchain.AddBlock(data)
	fmt.Println("正在添加新的区块...")
	//cli.sendToken()

	fmt.Println(cli.blockchain.FindSpentableOutputs("lidabao", 5))
	fmt.Println(cli.blockchain.FindSpentableOutputs("dandan", 3))
	fmt.Println(cli.blockchain.FindSpentableOutputs("awang", 2))
	for _, transaction := range cli.blockchain.FindUnspentTransactions("lidabao") {
		fmt.Println(*transaction)
	}
}

//验证参数的多少，避免数组越界问题
func (cli *CLI) ValidateAges() {
	if len(os.Args) < 2 {
		cli.PrintUsage()
		os.Exit(1)
	}
}

func (cli *CLI) Run() {
	cli.ValidateAges()
	addBlock := flag.NewFlagSet("addblock", flag.ExitOnError)
	printBlock := flag.NewFlagSet("printblock", flag.ExitOnError)

	data := addBlock.String("data", "", "这个东西是为了添加数据到data中")

	switch os.Args[1] {
	case "addblock":

		err := addBlock.Parse(os.Args[2:])
		if err != nil {
			panic(err)
		}

		fmt.Println("你要加入到区块链中的数据是:", *data)
	case "printblock":

		err := printBlock.Parse(os.Args[2:])
		if err != nil {
			fmt.Printf("%v\n", err)
		}

		fmt.Printf("正在打印区块链的信息......")
		cli.PrintBlockChain()
	default:

		cli.PrintUsage()

		fmt.Printf("请正确输入参数和命令！")
	}

	if addBlock.Parsed() {
		if *data == "" {
			fmt.Printf("你没有输入任何的数据进来!\n")
			cli.PrintUsage()
			os.Exit(1)
		} else {
			cli.AddBlock(*data)
		}
	}
}
